package com.anche.cywebnew.Utils.netsdk.product;

import com.anche.cywebnew.Utils.Thread.LxThreadPoolUtil;
import com.anche.cywebnew.Utils.netsdk.NetSDKLib;
import com.anche.cywebnew.Utils.netsdk.NetSDKLib.*;
import com.anche.cywebnew.Utils.netsdk.callback.DownLoadPosCallBackByTime;
import com.anche.cywebnew.Utils.netsdk.callback.DownloadCompleted;
import com.anche.cywebnew.Utils.netsdk.pojo.DownloadPara;

import java.util.*;
import java.util.concurrent.ThreadPoolExecutor;

import static com.anche.cywebnew.Utils.netsdk.NetSDKLib.*;

public class DahRecorder implements Recorder {

    public static NetSDKLib netsdk;
    public static NetSDKLib configsdk;


    public DahRecorder() {
        netsdk =  NETSDK_INSTANCE;
        configsdk = CONFIG_INSTANCE;
    }

    @Override
    public Map<String, Object> doInit() {
        Map<String, Object> result = new HashMap<>();
        boolean bInit;
        bInit = netsdk.CLIENT_Init(null, null);
        if (!bInit) {
            String msg = String.format("初始化SDK失败. %s", netsdk.CLIENT_GetLastError());
            result.put("code", "0");
            result.put("msg", msg);
        } else {
            result.put("code", "1");
        }
        return result;
    }

    @Override
    public Map<String, Object> doLogin(String ip, int port, String username, String password) {
        //登陆句柄
        LLong m_hLoginHandle = new LLong(0);
        Map<String, Object> result = new HashMap<>();
        //入参
        NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY pstInParam =
                new NET_IN_LOGIN_WITH_HIGHLEVEL_SECURITY();
        pstInParam.szIP = ip.getBytes();
        pstInParam.nPort = port;
        pstInParam.szUserName = username.getBytes();
        pstInParam.szPassword = password.getBytes();
        //出参
        NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY pstOutParam =
                new NET_OUT_LOGIN_WITH_HIGHLEVEL_SECURITY();
        m_hLoginHandle =
                netsdk.CLIENT_LoginWithHighLevelSecurity(pstInParam, pstOutParam);
        if (m_hLoginHandle.longValue() == 0) {
            String msg = String.format("登陆设备IP[%s] Port[%d]失败. %s", ip, port, netsdk.CLIENT_GetLastError());
            result.put("code", "0");
            result.put("msg", msg);
        } else {
            result.put("code", "1");
            result.put("loginHandle", m_hLoginHandle);
        }
        return result;
    }

//    @Override
//    public Map<String, Object> doDownload(Object m_hLoginHandle, DownloadPara downloadPara, DownloadCompleted completed) {
//        // 下载句柄
//        LLong m_hDownLoadHandle = new LLong(0);
//        /*
//         * 按时间下载回调
//         */
//        DownLoadPosCallBackByTime m_DownLoadPosByTime = new DownLoadPosCallBackByTime(); // 录像下载进度
//        Map<String, Object> result = new HashMap<>();
//        NET_TIME stTimeStart = convertDate(downloadPara.getStartDate());
//        NET_TIME stTimeEnd = convertDate(downloadPara.getEndDate());
//        m_hDownLoadHandle = netsdk.CLIENT_DownloadByTimeEx((LLong) m_hLoginHandle, downloadPara.getChannel(),
//                0, stTimeStart, stTimeEnd, downloadPara.getFilePath(), m_DownLoadPosByTime
//                , null, null, null, null);
//        m_DownLoadPosByTime.setM_hDownLoadHandle(m_hDownLoadHandle);
//        if (m_hDownLoadHandle.longValue() != 0) {
//            Timer timer = new Timer();
//            TimerTask timerTask = new TimerTask() {
//                @Override
//                public void run() {
//                    if (!m_DownLoadPosByTime.getMsg().equals("")) {
//                        if (m_DownLoadPosByTime.getMsg().contains("停止下载成功")) {
//                            completed.success(downloadPara.getId());
//                        } else {
//                            completed.failed(downloadPara.getId(), m_DownLoadPosByTime.getMsg());
//                        }
//                        timer.cancel();
//                    }
//                }
//            };
//            timer.schedule(timerTask, 1000, 1000);
//            result.put("code", "1");
//            result.put("downloadHandle", m_hDownLoadHandle);
//        } else {
//            String msg = String.format("开始下载录像失败. %s", ToolKits.getErrorCodePrint());
//            result.put("code", "0");
//            result.put("msg", msg);
//        }
//        return result;
//    }

    @Override
    public Map<String, Object> doDownload(Object m_hLoginHandle, List<DownloadPara> downloadParas) {
        Map<String, Object> result = new HashMap<>();
        ThreadPoolExecutor threadPool = LxThreadPoolUtil.getThreadPool();  // 获取公共线程池
        try {
            for (DownloadPara downloadPara : downloadParas) {
                // 线程池多线程执行
                threadPool.execute(new Runnable() {
                    @Override
                    public void run() {
                        DownloadCompleted completed = downloadPara.getCompleted();
                        // 下载句柄
                        NetSDKLib.LLong m_hDownLoadHandle = new NetSDKLib.LLong(0);
                        // 按时间下载回调
                        DownLoadPosCallBackByTime m_DownLoadPosByTime = new DownLoadPosCallBackByTime(); // 录像下载进度
                        NetSDKLib.NET_TIME stTimeStart = convertDate(downloadPara.getStartDate());
                        NetSDKLib.NET_TIME stTimeEnd = convertDate(downloadPara.getEndDate());
                        m_hDownLoadHandle = netsdk.CLIENT_DownloadByTimeEx((NetSDKLib.LLong) m_hLoginHandle, downloadPara.getChannel(),
                                0, stTimeStart, stTimeEnd, downloadPara.getFilePath(), m_DownLoadPosByTime
                                , null, null, null, null);
                        m_DownLoadPosByTime.setM_hDownLoadHandle(m_hDownLoadHandle);
                        while (true) {
                            try {
                                Thread.sleep(1000);
                                if (!m_DownLoadPosByTime.getMsg().equals("")) {
                                    if (m_DownLoadPosByTime.getMsg().contains("停止下载成功")) {
                                        completed.success(downloadPara.getId(), downloadPara.getFilePath());
                                    } else {
                                        completed.failed(downloadPara.getId(), m_DownLoadPosByTime.getMsg());
                                    }
                                    break;
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                                completed.failed(downloadPara.getId(), e.getMessage());
                                break;
                            }
                        }
                    }
                });
            }
            result.put("code","1");
        }catch (Exception e){
            result.put("code","1");
            result.put("msg",e.getMessage());
        }
        return result;
    }

    private NET_TIME convertDate(Date inputDate) {
        Calendar ca = Calendar.getInstance();
        ca.setTime(inputDate);                    //放入Date类型数据

        int year = ca.get(Calendar.YEAR);                    //获取年份
        int month = ca.get(Calendar.MONTH) + 1;                    //获取月份
        int day = ca.get(Calendar.DATE);                    //获取日

        int hour = ca.get(Calendar.HOUR_OF_DAY);                //时（24小时制）
        int minute = ca.get(Calendar.MINUTE);                    //分
        int second = ca.get(Calendar.SECOND);                    //秒
        NET_TIME output = new NET_TIME();
        output.dwYear = year;
        output.dwMonth = month;
        output.dwDay = day;
        output.dwHour = hour;
        output.dwMinute = minute;
        output.dwSecond = second;
        return output;
    }
}
